import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { message } from 'antd';
import AddQuestion from '../components/AddQuestion';
import axios from 'axios';
import { TYPE_MAP } from '../constants';

interface QuestionData {
  type: string;
  title: string;
  language: string[];
  codeAnswer: string;
  a: string;
  b: string;
  c: string;
  d: string;
  answer: string | string[];
}

type QuestionType = keyof typeof TYPE_MAP;

export default function EditQuestion() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [questionData, setQuestionData] = useState<QuestionData | null>(null);

  useEffect(() => {
    const fetchQuestion = async () => {
      if (!id) {
        console.log('No id provided, redirecting to question bank');
        message.error('题目ID不存在');
        navigate('/question-bank');
        return;
      }

      try {
        const response = await axios.get(`/api/questions/${id}`);
        console.log('Response received:', response.data);

        if (response.data.code === 0) {
          const data = response.data.data;
          // 转换数据格式以匹配表单
          const formData: QuestionData = {
            type: (Object.keys(TYPE_MAP).find(
              (key) => TYPE_MAP[key as QuestionType] === data.type
            ) || '') as QuestionType,
            title: data.content,
            language: data.language
              ? typeof data.language === 'string'
                ? data.language.startsWith('[')
                  ? JSON.parse(data.language)
                  : [data.language]
                : []
              : [],
            codeAnswer: data.type === '编程题' ? (data.answer ? JSON.parse(data.answer) : '') : '',
            a: data.options
              ? Array.isArray(JSON.parse(data.options)) && JSON.parse(data.options).length > 0
                ? JSON.parse(data.options)[0]
                : ''
              : '',
            b: data.options
              ? Array.isArray(JSON.parse(data.options)) && JSON.parse(data.options).length > 1
                ? JSON.parse(data.options)[1]
                : ''
              : '',
            c: data.options
              ? Array.isArray(JSON.parse(data.options)) && JSON.parse(data.options).length > 2
                ? JSON.parse(data.options)[2]
                : ''
              : '',
            d: data.options
              ? Array.isArray(JSON.parse(data.options)) && JSON.parse(data.options).length > 3
                ? JSON.parse(data.options)[3]
                : ''
              : '',
            answer:
              data.type === '多选题'
                ? Array.isArray(JSON.parse(data.answer))
                  ? JSON.parse(data.answer)
                  : [JSON.parse(data.answer)]
                : data.type === '单选题'
                  ? JSON.parse(data.answer)
                  : data.answer
          };
          console.log('Formatted data:', formData);
          setQuestionData(formData);
        } else {
          console.error('API Error:', response.data.message);
          // message.error('获取题目数据失败');
          navigate('/question-bank');
        }
      } catch (error) {
        console.error('Error fetching question:', error);
        navigate('/question-bank');
        message.error('获取题目数据失败');
      } finally {
        setLoading(false);
      }
    };

    fetchQuestion();
  }, [id, navigate]);

  if (loading) {
    return <div>加载中...</div>;
  }

  if (!questionData) {
    return <div>未找到题目数据</div>;
  }

  return (
    <div style={{ backgroundColor: '#f5f5f5', paddingTop: 8,paddingBottom:4,borderRadius:2 }}>
      <AddQuestion title="编辑题目" initialValues={questionData} isEdit={true} questionId={id} />
    </div>
  );
}
